package com.jf.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf.blog.bean.Blog;
import com.jf.blog.bean.Category;
import com.jf.blog.form.CategorySearchForm;
import com.jf.blog.mapper.CategoryMapper;
import com.jf.blog.service.BlogService;
import com.jf.blog.service.CategoryService;
import com.jf.blog.util.ResultJson;
import com.jf.blog.util.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客分类表 服务实现类
 * </p>
 *
 * @author JF
 * @since 2025-06-20
 */
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private BlogService blogService;

    @Override
    public ResultJson getPage(int page, int limit, CategorySearchForm searchForm) {
        IPage<Category> iPage = this.page(new Page<>(page, limit),
                new QueryWrapper<Category>()
                        .eq(StringUtils.isNotEmpty(searchForm.getName()), "name", searchForm.getName())
                        .eq(searchForm.getStatus() != null, "status", searchForm.getStatus())
                        .orderByDesc("create_time")
        );
        return ResultJson.success(iPage);
    }

    @Override
    public void delete(List<Integer> categoryIds) {
        /*去重查询列表*/
        List<Blog> blogList = blogService.list(new QueryWrapper<Blog>()
                /*where category in (?,?,?...?)*/
                .in("category_id", categoryIds)
                /*根据category_id的值去重查询,注意结果集合中值包含categoryId的值*/
                .select("distinct category_id"));
        if (!blogList.isEmpty()) {
            List<Integer> ids = blogList.stream().map(Blog::getCategoryId).collect(Collectors.toList());
            throw new BusinessException(ids + "存在关联数据,禁止删除!");
        }
        this.removeByIds(categoryIds);
    }

    @Override
    public ResultJson select() {
        return ResultJson.success(this.list(new QueryWrapper<Category>().orderByDesc("create_time")));
    }
}
